<?php
/**
 * Created by PhpStorm.
 * User: luzy
 * Date: 2018/4/9
 * Time: 下午2:20
 */
require_once APPPATH.'third_party/wxpayapi/lib/phpqrcode.php';
class Salesman_post_model extends Base_Model
{
    private $_appid;
    private $_appsecret;
    private $_wx_type;
    private $_source;
    private $_redis;
    private $_postdir;
    private $_postdbdir;

    public function __construct()
    {
        parent::__construct();
        $this->_source = "nldou_fuwu";
        $this->load->config('weixin');
        $this->_appid = $this->config->item($this->_source.'_appid');
        $this->_appsecret = $this->config->item($this->_source.'_appsecret');
        $this->_wx_type = $this->config->item($this->_source.'_type');
        $this->_postdir = "/home/nldou/webroot/wap/upload/images/salesman/v2/";
        $this->_postdbdir = "/upload/images/salesman/v2/";
        $this->load->database();
    }

    public function getPostType()
    {
        return $this->db->from('mod_slspost_type')->where('status = 1')->get()->result_array();
    }
    public function getSlsPosts($postType,$sls,$offset=0,$limit=10)
    {
        $this->db->from('mod_salesman_post_v2');
        if ($postType>0){
            $this->db->where('type =',$postType);
        }
        $this->db->where('status = 1');
        $posts = $this->db->order_by('sort','ASC')
            ->limit($limit,$offset)
            ->get()->result_array();

        $end = 0;
        $this->db->where(array('status' => 1));
        if ($postType > 0) {
            $this->db->where('type =', $postType);
        }
        $total = $this->db->count_all_results('mod_salesman_post_v2');
        $listsize = $limit+$offset;
        if ($total<$listsize||$total==$listsize) $end=1;

        $res = array();
        if (!empty($posts)){
            if (!isset($this->_redis)){
                $this->load->model('redis_model');
                $this->_redis=$this->redis_model->getRedisInstance();
            }
            foreach ($posts as $row){
                $post=$this->_redis->get('slspostv2.'.$row['id'].'.'.$sls);
                //缓存不存在
                if ($post===false){
                    $post = $this->createSlsPost($row,$sls);
                    if ($post!==false) {
                        //成功生成海报
                        $res[]='http://wap.nldou.com'.$post;
                    }
                }else{$res[]='http://wap.nldou.com'.$post;}
            }
        }
        return array('list'=>$res,'end'=>$end);
    }

    public function createSlsPost($oripost,$sls)
    {
        //生成二维码解析地址
        $route = $this->db->get_where('mod_slspost_route','pid ='.$oripost['pid'])->row_array();
        switch ((int)$route['linktype']){
            case 1:/*有赞链接*/
            case 2:/*自定义链接*/
                $url = "http://api.nldou.com/salesman/postv2/scan?pid=".$oripost['pid']."&sls=".$sls."&postid=".$oripost['id'];
                // $url = $this->longurl2short($url);
                $redistimeout = 0;
                break;
            case 3:/*公众号带参数二维码*/
                $url = $this->getWxQrcode($oripost['pid'],$oripost['id'],$sls);
                $redistimeout = 24*3600*25;
                break;
            default:
                return false;
        }

        //生成二维码解析地址出现错误
        if ($url===false){return false;}
        //生成二维码
        $qrcode = $this->qrcode($url,$oripost['id'],$sls,'/qrcode/');
        //处理二维码
        $config=array();
        $config['source_image']=$qrcode['file'];//源文件地址
        $qrpath=$qrcode['dir'].$oripost['id'].$sls.$qrcode['time'].'.png';//处理后地址
        $config['new_image']=$qrpath;
        $config['height']=$oripost['qrheight'];
        $config['width']=$oripost['qrwidth'];
        $this->resize($config);
        //添加二维码到海报
        $config=array();
        $config['wm_vrt_alignment']='top';
        $config['wm_hor_alignment']='left';
        $config['source_image']='/home/nldou/webroot/wap'.$oripost['url'];//海报模板地址
        $newdir=$this->_postdir.$oripost['id'].'/post/';
        if(!file_exists($newdir)){
            mkdir($newdir,0775,true);
        }
        $postpath=$newdir.$oripost['id'].$sls.$qrcode['time'].'.jpg';//处理后海报地址

        $posturl=$this->_postdbdir.$oripost['id'].'/post/'.$oripost['id'].$sls.$qrcode['time'].'.jpg';
        $config['new_image']=$postpath;
        $config['wm_type']='overlay';
        $config['wm_opacity']='100';
        $config['wm_overlay_path']=$qrpath;
        $config['wm_hor_offset']=(string)$oripost['hor'];
        $config['wm_vrt_offset']=(string)$oripost['vrt'];
        $this->overlay($config);
        //存入redis
        if (!isset($this->_redis)){
            $this->load->model('redis_model');
            $this->_redis=$this->redis_model->getRedisInstance();
        }
        if ($redistimeout===0){
            $this->_redis->set('slspostv2.'.$oripost['id'].'.'.$sls,$posturl);
        }else{$this->_redis->set('slspostv2.'.$oripost['id'].'.'.$sls,$posturl,$redistimeout);}

        return $posturl;
    }

    public function getInviPosts($sls,$offset=0,$limit=10)
    {
        $posts = $this->db->from('mod_salesman_invipost')
            ->where('status = 1')
            ->order_by('sort','ASC')
            ->limit($limit,$offset)
            ->get()->result_array();

        $res = array();
        if (!empty($posts)){
            if (!isset($this->_redis)){
                $this->load->model('redis_model');
                $this->_redis=$this->redis_model->getRedisInstance();
            }
            foreach ($posts as $row){
                $post=$this->_redis->get('slsinvipost.'.$row['id'].'.'.$sls);
                //缓存不存在
                if ($post===false){
                    $post = $this->createInviPost($row,$sls);
                    if ($post!==false) {
                        //成功生成海报
                        $res[]='http://wap.nldou.com'.$post;
                    }
                }else{$res[]='http://wap.nldou.com'.$post;}
            }
        }
        return $res;
    }

    public function createInviPost($oripost,$sls)
    {
        $url = "https://wap.youzan.com/salesman/home/tutorial?kdt_id=18168297&from_seller=".$sls;
        // $url = $this->longurl2short($url);

        //生成二维码解析地址出现错误
        if ($url===false){return false;}
        //生成二维码
        $qrcode = $this->qrcode($url,$oripost['id'],$sls,'/inviqrcode/');
        //处理二维码
        $config=array();
        $config['source_image']=$qrcode['file'];//源文件地址
        $qrpath=$qrcode['dir'].$oripost['id'].$sls.$qrcode['time'].'.png';//处理后地址
        $config['new_image']=$qrpath;
        $config['height']=$oripost['qrheight'];
        $config['width']=$oripost['qrwidth'];
        $this->resize($config);
        //添加二维码到海报
        $config=array();
        $config['wm_vrt_alignment']='top';
        $config['wm_hor_alignment']='left';
        $config['source_image']='/home/nldou/webroot/wap'.$oripost['url'];//海报模板地址
        $newdir=$this->_postdir.$oripost['id'].'/invipost/';
        if(!file_exists($newdir)){
            mkdir($newdir,0775,true);
        }
        $postpath=$newdir.$oripost['id'].$sls.$qrcode['time'].'.jpg';//处理后海报地址

        $posturl=$this->_postdbdir.$oripost['id'].'/invipost/'.$oripost['id'].$sls.$qrcode['time'].'.jpg';
        $config['new_image']=$postpath;
        $config['wm_type']='overlay';
        $config['wm_opacity']='100';
        $config['wm_overlay_path']=$qrpath;
        $config['wm_hor_offset']=(string)$oripost['hor'];
        $config['wm_vrt_offset']=(string)$oripost['vrt'];
        $this->overlay($config);
        //存入redis
        if (!isset($this->_redis)){
            $this->load->model('redis_model');
            $this->_redis=$this->redis_model->getRedisInstance();
        }
        $this->_redis->set('slsinvipost.'.$oripost['id'].'.'.$sls,$posturl);

        return $posturl;
    }

    public function longurl2short($url)
    {
        if (!isset($this->wxinterface)){
            $this->load->library("wxinterface/Wxinterface",array("appid"=>$this->_appid,"appsecret"=>$this->_appsecret,"wxtype"=>$this->_wx_type));
        }
        $res=$this->wxinterface->longurl2short($url);
        if ($res['errcode']==0){
            return $res['short_url'];
        }

        return false;
    }

    public function getWxQrcode($sceneid,$postId,$sls)
    {
        $sceneval = $sceneid.".".$sls.".".$postId;
//        log_message('error',$sceneval);
        if (!isset($this->wxinterface)){
            $this->load->library("wxinterface/Wxinterface",array("appid"=>$this->_appid,"appsecret"=>$this->_appsecret,"wxtype"=>$this->_wx_type));
        }
        $res = $this->wxinterface->getWxQrcode("QR_STR_SCENE",$sceneval);
        if (isset($res['url'])){
            return $res['url'];
        }

        return false;
    }

    public function qrcode($url,$postId,$sls,$dir)
    {
        $filedir=$this->_postdir.$postId.$dir;
        if(!file_exists($filedir)){
            mkdir($filedir,0775,true);
        }
        $timestamp = time();
        $filepath=$filedir.$postId.$sls.$timestamp.'_raw.png';
        QRcode::png($url,$filepath,'QR_ECLEVEL_L',8,3);
        return array('dir'=>$filedir,'file'=>$filepath,'time'=>$timestamp);
    }

    public function changeUserIcon($sls,$icon)
    {
        $uidres = $this->db->select('uid')->from('mod_salesman')->where('idcode =',$sls)->get()->row_array();
//        log_message('error',$sls);
//        log_message('error',$uidres['uid']);
        if ($uidres['uid']==0) return;
        $data['userIcon'] = $icon;
        return $this->db->update('mod_user',$data,'uid='.$uidres['uid']);
    }

    public function resize($config=array())
    {
        if (!isset($config['source_image'])||empty($config['source_image'])) {
            echo 'no source image'.PHP_EOL;
            exit();
        }
        if (!isset($this->image_lib)){
            $this->load->library('image_lib');
        }
        $this->image_lib->initialize($config);
        if (!$this->image_lib->resize()){
            echo $this->image_lib->display_errors();
            exit();
        }
        $this->image_lib->clear();
    }

    public function overlay($config=array())
    {
        if (!isset($config['source_image'])||empty($config['source_image'])) {
            echo 'no source image'.PHP_EOL;
            exit();
        }
        if (!isset($this->image_lib)){
            $this->load->library('image_lib');
        }
        $this->image_lib->initialize($config);
        if (!$this->image_lib->watermark()){
            echo $this->image_lib->display_errors();
            exit();
        }
        $this->image_lib->clear();
    }

    public function getRedirectPage($pid,$sls)
    {
        $link = $this->db->select('link,linktype')->from('mod_slspost_route')->where('pid =',$pid)->get()->row_array();
        if (empty($link)) return false;
        $linkstr = $link['link'];
        $linktype = (int)$link['linktype'];
        $res = false;
        switch ($linktype){
            //有赞商城链接
            case 1:
                $res = "https://h5.youzan.com/v2/trade/directsellerJump/jump?kdt_id=18168297&sl=".$sls."&redirect_uri=".urlencode($linkstr."?sls=".$sls);
                break;
            //非有赞自定义链接
            case 2:
                $res = $linkstr;
                break;
        }
        return $res;
    }

    public function saveScanStat($pid,$postid,$uid,$sls)
    {
        if (!isset($this->_redis)){
            $this->load->model('redis_model');
            $this->_redis=$this->redis_model->getRedisInstance();
        }
        $data = array('pid'=>$pid,'uid'=>$uid,'timestamp'=>time(),
            'postid'=>$postid,'sls'=>$sls);
        $datastr = json_encode($data);
        $this->_redis->rPush('slspostv2.scan.stat',$datastr);
    }
}